package com.sneakxy.jdbc;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.sneakxy.config.Jdbc;

/**
 * Oracle方言
 * @author 潜行的青衣
 * @see
 */
public class OracleDialect implements Dialect {

	/* (non-Javadoc)
	 * @see com.sneakxy.mybase4j.generator.jdbc.Dialect#setUrl(java.lang.String)
	 */
	@Override
	public void setUrl(String url) {}

	/* (non-Javadoc)
	 * @see com.sneakxy.mybase4j.generator.jdbc.Dialect#getTablesSql()
	 */
	@Override
	public String getTablesSql() {
		return "select table_name from all_tables";
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.mybase4j.generator.jdbc.Dialect#getSelectNone(java.lang.String)
	 */
	@Override
	public String getSelectNone(String table) {
		return StringUtils.join("select * from ", table, " where 1!=1");
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.mybase4j.generator.jdbc.Dialect#getCatalog()
	 */
	@Override
	public String getCatalog(Jdbc jdbc, String tableName) {
		return getSchema(jdbc, tableName);
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.mybase4j.generator.jdbc.Dialect#getSchema()
	 */
	@Override
	public String getSchema(Jdbc jdbc, String tableName) {
		if(StringUtils.contains(tableName, ".")) {
			return StringUtils.upperCase(StringUtils.split(tableName, ".")[0]);
		}
		return StringUtils.upperCase(jdbc.getUsername());
	}

	@Override
	public String getCreateSql(String tableName, String sql, String charset) {
		return StringUtils.join("CREATE TABLE ", tableName, sql, ";");
	}

	@Override
	public String getCreateUnionSql(List<String> union, String tableName, String sql, String charset) {
		StringBuilder s = new StringBuilder();
		s.append("(");
		Iterator<String> it = union.iterator();
		String table = null;
		while(it.hasNext()) {
			table = it.next();
			s.append("SELECT * FROM ").append(table);
			if(it.hasNext()) {
				s.append(" UNION ");
			}
		}
		s.append(")");
		return StringUtils.join("CREATE OR REPLACE VIEW ", tableName, " AS ", s.toString(), ";");
	}

	@Override
	public String[] getAlterTableSql(List<String> union, String tableName,  String alterSql, String createSql, String charset) {
		return new String[] {getCreateUnionSql(union, tableName, createSql, charset)};
	}

}
